package com.smm.web.vmc.api;


import com.smm.web.vmc.domain.User;
import com.smm.web.vmc.domain.relation.UserReceiptRelation;
import com.smm.web.vmc.dto.JsonReturn;
import com.smm.web.vmc.service.UserReceiptRelationService;
import com.smm.web.vmc.service.UserService;
import com.smm.web.vmc.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping(value = "/api/user",method = RequestMethod.POST)
public class UserApi {

    @Resource
    private UserService userService;

    @Resource
    private UserReceiptRelationService userReceiptRelationService;


    //修改密码
    @RequestMapping("/updatePassword")
    @ResponseBody
    public JsonReturn updatePassword(String account,String oldPassword,String newPassword){

        try{

            if(StringUtils.isBlank(oldPassword)) throw new Exception("原密码为空");

            if(StringUtils.isBlank(newPassword)) throw new Exception("新密码为空");

            User user = this.userService.login(account,oldPassword);

            if(user==null) throw new Exception("原密码不正确");

            newPassword = MD5Util.parseStrToMd5L32(newPassword);

            user.setPassword(newPassword);

            this.userService.update(user);

        }catch (Exception e){

            e.printStackTrace();

            return new JsonReturn(0,e.getMessage());
        }

        return new JsonReturn(1,"更新成功");

    }


    //检查用户是否有权限查看仓单
    @RequestMapping("/checkdPurviewForReceipt")
    @ResponseBody
    public JsonReturn checkdPurviewForReceipt(int userId,String repNo){

        try{

            UserReceiptRelation urr = this.userReceiptRelationService.getReceiptByUserAndRepNo(userId,repNo);

            if(urr==null) throw new Exception("没有访问权限");

            return new JsonReturn(1,"有访问权限",repNo);

        }catch (Exception e){

            return new JsonReturn(0,e.getMessage());
        }
    }


    //检查用户是否有权限查看摄像头
    @RequestMapping("/checkPurviewForCamera")
    @ResponseBody
    public JsonReturn checkPurviewForCamera(int userId,int cameraId){

        try{

            boolean isPurview = this.userService.checkPurviewForCamera(userId,cameraId);

            if(!isPurview) throw new Exception("没有访问权限");

            return new JsonReturn(1,"有访问权限",cameraId);

        }catch (Exception e){

            return new JsonReturn(0,e.getMessage());
        }
    }


}

